//
// This file is part of cpp-lib, a library of C++ functions and classes.
// Cpp-lib is copyright (C) 2004 and onwards, The CPL Interest Group.
// 
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version.
// 
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this library (see the file COPYING); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
// 02111-1307  USA
//
// $Id$
//

#include <iostream>
#include <string>

#include <cassert>

#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>


#include "cpp-lib/util.h"
#include "cpp-lib/realtime.h"

using namespace cpl::util ;


void usage() 
{ std::cerr << "usage: sched-thread-test <dt1> <dt2>\n" ; }


struct cerr_thread {

  cerr_thread( double const& dt ) : dt( dt ) {}

  void operator()() ;
  
private:

  double dt ;

} ;
  

void cerr_thread::operator()() {

  while( 1 ) { 
	
	std::cerr << "cerr thread" << std::endl ; 

    cpl::util::sleep( dt ) ;
  
  }

}



int main( int const argc , char const * const * const argv ) {

  if( argc != 3 ) { usage() ; return 1 ; }

  try {

  double const dt1 = boost::lexical_cast< double >( argv[ 1 ] ) ;
  double const dt2 = boost::lexical_cast< double >( argv[ 2 ] ) ;

  if( dt1 <= 0 || dt2 <= 0 ) { usage() ; return 1 ; }


  //
  // Create the scheduler *before* the thread to have it inherit the
  // blocked signal.
  //

  realtime_scheduler s( dt1 ) ;
  
  //
  // Extreme care here.  boost::thread t( cerr_thread( dt2 ) ) is
  // somehow misinterpreted as a function declaration (?).
  //

  boost::thread( cerr_thread( dt2 ) ) ;

  std::cout.precision( 16 ) ;

  while( 1 ) 
  { std::cout << s.wait_next() << std::endl ; }

  } catch( std::exception const& e ) 
  { std::cerr << e.what() << std::endl ; return 1 ; }

}
